﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeDDD.Application.Framework;
using System.Web.Mvc;

namespace CodeDDD.Presentation.MVC
{
    public abstract class CrudController<TEntityDTO, TIdentity> : BaseController
        where TEntityDTO : class, new()
    {
        #region Atributos

        protected ICrudAppService<TEntityDTO, TIdentity> appService;

        #endregion

        #region Construtor

        public CrudController(ICrudAppService<TEntityDTO, TIdentity> appService)
        {
            if (appService == null)
                throw new ArgumentNullException("appService");

            this.appService = appService;
        }

        #endregion

        #region Actions

        public virtual ActionResult Index()
        {
            return View();
        }

        public virtual ActionResult Details(TIdentity id)
        {
            return View(appService.Get(id));
        }

        [HttpGet]
        public virtual ActionResult Create()
        {
            return View(new TEntityDTO());
        }

        [HttpPost]
        public virtual ActionResult Create(TEntityDTO dto)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    appService.Add(dto);

                    return RedirectToAction("Index");
                }

                return View(dto);
            }
            catch
            {
                return View();
            }
        }

        public virtual ActionResult Edit(TIdentity id)
        {
            return View(appService.Get(id));
        }

        [HttpPost]
        public virtual ActionResult Edit(TEntityDTO dto)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    appService.Update(dto);

                    return RedirectToAction("Index");
                }

                return View(dto);
            }
            catch
            {
                return View();
            }
        }

        public virtual ActionResult Delete(TIdentity id)
        {
            return View(appService.Get(id));
        }

        [HttpPost]
        public virtual ActionResult Delete(TIdentity id, FormCollection collection)
        {
            try
            {
                appService.Remove(id);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        #endregion
    }
}
